package com.itfitness.bluetoothdemo

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.itfitness.bluetoothdemo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private var bluetoothAdapter: BluetoothAdapter? = null
    private lateinit var activityMainBinding: ActivityMainBinding
    private lateinit var openBluetoothActivityForResult:ActivityResultLauncher<Intent>
    private lateinit var deviceAdapter: BaseQuickAdapter<String,BaseViewHolder>
    private val deviceList = ArrayList<String>() //设备列表
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityMainBinding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
        activityMainBinding.lifecycleOwner = this

        initBluetooth()

        registerActivityResultLauncher()

        registerBluetoothScan()

        initListener()

        preDeviceAdapter()
    }

    /**
     * 获取蓝牙BluetoothAdapter
     */
    private fun initBluetooth() {
        val bluetoothManager =  getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
    }

    private fun preDeviceAdapter() {
        deviceAdapter = object :BaseQuickAdapter<String,BaseViewHolder>(R.layout.item_bluetooth,deviceList){
            override fun convert(holder: BaseViewHolder, item: String) {
                val tvDeviceName = holder.getView<TextView>(R.id.tv_deviceName)
                tvDeviceName.text = item
            }
        }
        activityMainBinding.rvBluetooth.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = deviceAdapter
        }
    }

    /**
     * 注册扫描蓝牙的广播
     */
    private fun registerBluetoothScan() {
        registerReceiver(bluetoothScanBroadcastReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
        registerReceiver(bluetoothScanBroadcastReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
        registerReceiver(bluetoothScanBroadcastReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
    }

    private fun initListener() {
        activityMainBinding.btOpenBluetooth.setOnClickListener {
            checkBluetooth()
        }

        activityMainBinding.btScanBluetooth.setOnClickListener {
            scanBluetooth()
        }
    }

    /**
     * 注册请求开启蓝牙的Launcher
     */
    private fun registerActivityResultLauncher() {
        openBluetoothActivityForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result->
            if (result.resultCode == RESULT_OK) {
                ToastUtils.showShort("蓝牙开启")
            }else{
                ToastUtils.showShort("未能开启")
            }
        }
    }

    /**
     * 扫描蓝牙
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun scanBluetooth() {
        deviceList.clear()
        deviceAdapter.notifyDataSetChanged()
        bluetoothAdapter?.startDiscovery()
    }

    /**
     * 检测是否支持蓝牙
     */
    private fun checkBluetooth() {
        if(bluetoothAdapter == null){
            ToastUtils.showShort("没有蓝牙")
            return
        }else{
            ToastUtils.showShort("有蓝牙")
            openBluetooth()
        }
    }

    /**
     * 请求打开蓝牙
     */
    private fun openBluetooth() {
        bluetoothAdapter?.let {
            if(!it.isEnabled){
                ToastUtils.showShort("即将开启蓝牙")
                val openBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                openBluetoothActivityForResult.launch(openBluetoothIntent)
            }else{
                ToastUtils.showShort("蓝牙以开启")
            }
        }
    }

    private val bluetoothScanBroadcastReceiver = object :BroadcastReceiver(){
        @SuppressLint("NotifyDataSetChanged")
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                when(it.action){
                    //开始扫描
                    BluetoothAdapter.ACTION_DISCOVERY_STARTED->{
                        ToastUtils.showShort("开始扫描")
                        LogUtils.eTag("蓝牙","开始扫描")
                    }
                    //扫描到设备
                    BluetoothDevice.ACTION_FOUND->{
                        it.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)?.let { device->
                            device.name?.let {
                                LogUtils.eTag("蓝牙",device.name)
                                deviceList.add(device.name)
                                deviceAdapter.notifyDataSetChanged()
                            }
                        }
                    }
                    //扫描结束
                    BluetoothAdapter.ACTION_DISCOVERY_FINISHED->{
                        ToastUtils.showShort("扫描结束")
                        LogUtils.eTag("蓝牙",deviceList)
                    }
                    else -> {
                        ToastUtils.showShort("其他")
                        LogUtils.eTag("蓝牙","其他")
                    }
                }
            }
        }
    }
}